#!/bin/bash

exec 2>>/var/log/update_config_files.log
set -x

conf="$(cat /etc/gosa-si/server.conf /etc/gosa-si/client.conf | tr -d ' \t')"

ldap_config=$(echo "$conf" | sed -n -r 's/^ldap-config=(.*)/\1/p' | tail -n 1)
test -z "$ldap_config" && ldap_config=/etc/ldap/ldap.conf
pam_config=$(echo "$conf" | sed -n -r 's/^pam-config=(.*)/\1/p' | tail -n 1)
test -z "$pam_config" && pam_config=/etc/pam_ldap.conf
nss_config=$(echo "$conf" | sed -n -r 's/^nss-config=(.*)/\1/p' | tail -n 1)
test -z "$nss_config" && nss_config=/etc/libnss-ldap.conf
offline_enabled=$(echo "$conf" | sed -n -r 's/^offline-ldap=(.*)/\1/p' | tail -n 1)
test -z "$offline_enabled" && offline_enabled=0
ldap_config_exit_hook=$(echo "$conf" | sed -n -r 's/^ldap-config-exit-hook=(.*)/\1/p' | tail -n 1)
test -z "$ldap_config_exit_hook" && ldap_config_exit_hook="/bin/true"

test -n "$new_ldap_config" && {
  echo >$ldap_config "# Auto-generated by $0. Do not edit manually!
URI $(echo -n "$ldap_uri" | tr '\n' ' ')
BASE $ldap_base"
  for cfg in $ldap_cfg ; do echo >>$ldap_config $cfg ; done

  echo >$pam_config "# Auto-generated by $0. Do not edit manually!
uri $(echo -n "$ldap_uri" | tr '\n' ' ')
base $ldap_base"
  for cfg in $pam_cfg ; do echo >>$pam_config $cfg ; done

  echo >$nss_config "# Auto-generated by $0. Do not edit manually!
uri $(echo -n "$ldap_uri" | tr '\n' ' ')
base $ldap_base"
  for cfg in $nss_cfg ; do echo >>$nss_config $cfg ; done
  
  ldap_server=$(echo "$ldap_uri" | sed -n '1s%^ldap[^:]*://%%p')
  echo >/etc/ldap/ldap-shell.conf "LDAP_BASE=\"$ldap_base\"
LDAP_SERVER=\"$ldap_server\"
LDAP_URIS=\"$(echo -n "$ldap_uri" | tr '\n' ' ')\"
ADMIN_BASE=\"$admin_base\"
DEPARTMENT=\"$department\"
RELEASE=\"$release\"
UNIT_TAG=\"$unit_tag\""
  test -z "$unit_tag" &&  echo >>/etc/ldap/ldap-shell.conf "UNIT_TAG_FILTER=\"\""
  test -n "$unit_tag" &&  echo >>/etc/ldap/ldap-shell.conf "UNIT_TAG_FILTER=\"(gosaUnitTag=$unit_tag)\""

  test "$offline_enabled" = 1 && {
    echo >/etc/ldap/ldap-offline.conf "LDAP_BASE=\"$ldap_base\"
LDAP_SERVER=\"127.0.0.1\"
LDAP_URIS=\"ldap://127.0.0.1\"
ADMIN_BASE=\"$admin_base\"
DEPARTMENT=\"$department\"
RELEASE=\"$release\"
UNIT_TAG=\"$unit_tag\""
    test -z "$unit_tag" &&  echo >>/etc/ldap/ldap-offline.conf "UNIT_TAG_FILTER=\"\""
    test -n "$unit_tag" &&  echo >>/etc/ldap/ldap-offline.conf "UNIT_TAG_FILTER=\"(gosaUnitTag=$unit_tag)\""
  }
  
  "$ldap_config_exit_hook"
}

test -n "$new_ntp_config" && {
  true
}

exit 0
